package com.example.ycdyus.dailyfruit.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.ycdyus.dailyfruit.R;
import com.example.ycdyus.dailyfruit.adapter.DefaultListAdapter;
import com.example.ycdyus.dailyfruit.adapter.DemoAdapter;
import com.example.ycdyus.dailyfruit.adapter.HomeHeadViewPagerAdapter;
import com.example.ycdyus.dailyfruit.adapter.HomeListViewAdapter;
import com.example.ycdyus.dailyfruit.bean.Banner;
import com.example.ycdyus.dailyfruit.bean.DemoItem;
import com.example.ycdyus.dailyfruit.bean.HomeBaseBean;
import com.example.ycdyus.dailyfruit.constant.URLConstant;
import com.example.ycdyus.dailyfruit.constant.Variable;
import com.example.ycdyus.dailyfruit.request.FastJsonRequest;
import com.example.ycdyus.dailyfruit.ui.QiangxianActivity;
import com.example.ycdyus.dailyfruit.utils.ImageLoaderHelper;
import com.example.ycdyus.dailyfruit.utils.VolleyHelper;
import com.felipecsl.asymmetricgridview.library.Utils;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridView;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridViewAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    private ViewPager vpHomeHeadImg;
    private GridView gvHomeHeadCategory;
    private LinearLayout llHomeHead;
    private LinearLayout llHomeHorizontalProductBanner;
    private GridView gvHomeMixProductBanner;

    private PullToRefreshListView pullToRefreshListView;
    private DisplayImageOptions options;
    //ViewPager
    private HomeHeadViewPagerAdapter headViewPagerAdapter;
    private List<View> list = new ArrayList<>();
    private List<ImageView> listDot;
    private LinearLayout llDot;
    //分类GridView
    private SimpleAdapter simpleAdapter;
    private List<Map<String, Object>> simpleAdapterlist = new ArrayList<>();

    //主ListView
    private List<Banner> mainList  = new ArrayList<>();
    private HomeListViewAdapter listViewAdapter;

    //自定义
    private DemoAdapter adapterDemo;
    private AsymmetricGridView myGridView;
    private List<DemoItem> items = new ArrayList<>();
    private AsymmetricGridViewAdapter asymmetricGridViewAdapter;

    private HeadView headView;

    public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        headView = new HeadView();
        initViews(view);
        initData();
        return view;
    }

    private void initViews(View view) {
        pullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.main_home_pulltorefresh);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        options = ImageLoaderHelper.getDisplayImageLoader();
        pullToRefreshListView.getRefreshableView().addHeaderView(headView.getHeadViews());
    }

    private Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("sign", "a286d46bbaec46a42298e95b185fbf3a");
        params.put("timestamp", "1438873575");
        params.put("platform", "ANDROID");
        params.put("source", "app");
        params.put("connect_id", "");
        params.put("region_id", "143949");
        params.put("service", "marketing.banner");
        params.put("device_id", "93789e8978f2eefdcf52006b4d96ee23");
        params.put("channel", "qq");
        params.put("version", "2.3.0");
        return params;
    }

    private void initData() {
        listViewAdapter = new HomeListViewAdapter(getActivity(),mainList,R.layout.item_home_listview);
        pullToRefreshListView.getRefreshableView().setAdapter(listViewAdapter);
        FastJsonRequest<HomeBaseBean> requests = new FastJsonRequest<HomeBaseBean>(Request.Method.POST, URLConstant.MAIN_HOME_POST, getParams(), HomeBaseBean.class, new Response.Listener<HomeBaseBean>() {
            @Override
            public void onResponse(HomeBaseBean response) {
                initDataViewPager(response.getRotation());
                initDataLinerlayout(response.getTop_banner());
                initDataLinerlayoutHor(response.getHorizontal_product_banner());
                initMainList(response.getBanner());
                initMyGrid(response.getMix_product_banner());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        VolleyHelper.getInstance().addRequest(requests, this);
    }

    private void initMyGrid(List<Banner> mix) {
        myGridView.setRequestedColumnCount(15);
        myGridView.setRequestedHorizontalSpacing(Utils.dpToPx(getActivity(), 4));



        adapterDemo = new DefaultListAdapter(getActivity(), items);
        myGridView.setAdapter(getNewAdapter());
        myGridView.setDebugging(true);
        items.add(new DemoItem(6, 0, 8, mix.get(0).getPhoto()));
        items.add(new DemoItem(9, 0, 4, mix.get(1).getPhoto()));
        items.add(new DemoItem(9, 0, 4, mix.get(2).getPhoto()));
        myGridView.setAllowReordering(true);
    }

    private void initMainList(List<Banner> banner) {
        if(banner!=null){
            mainList.addAll(banner);
            listViewAdapter.notifyDataSetChanged();
        }
    }

    private AsymmetricGridViewAdapter<?> getNewAdapter() {
        return new AsymmetricGridViewAdapter<>(getActivity(), myGridView, adapterDemo);
    }

    private void initDataLinerlayoutHor(List<Banner> rotation) {
        if (rotation != null) {
            for (int i = 0; i < rotation.size(); i++) {
                ImageView iv = new ImageView(getActivity());
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,1);
                iv.setLayoutParams(param);
                ImageLoader.getInstance().displayImage(rotation.get(i).getPhoto(), iv, options);
                llHomeHorizontalProductBanner.addView(iv);
            }
        }
    }

    private void initDataLinerlayout(List<Banner> rotation) {
        llHomeHead.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, rotation.size()*240, 1));
        if (rotation != null) {
            for (int i = 0; i < rotation.size(); i++) {
                ImageView iv = new ImageView(getActivity());
                iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,1);
                iv.setLayoutParams(param);
                ImageLoader.getInstance().displayImage(rotation.get(i).getPhoto(), iv, options);
                llHomeHead.addView(iv);
            }
        }
    }

    private void initDataViewPager(List<Banner> top_banner) {
        for (int i = 0; i < top_banner.size(); i++) {
            ImageView iv = new ImageView(getActivity());
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(param);
            ImageLoader.getInstance().displayImage(top_banner.get(i).getPhoto(), iv, options);
            list.add(iv);
        }
        headViewPagerAdapter.notifyDataSetChanged();

        // 页面图片的点
        listDot = new ArrayList<>();
        for (int i = 0; i < top_banner.size(); i++) {
            ImageView iv = new ImageView(getActivity());
            // 设置图片
            if (i == 0) {
                iv.setImageResource(R.mipmap.dot);
            } else {
                iv.setImageResource(R.mipmap.dot_1);
            }
            // 设置图片的宽高
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(30, 30);
            iv.setLayoutParams(params);
            listDot.add(iv);
            // 向ll_bottom加点
            llDot.addView(iv);
        }

        vpHomeHeadImg.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 先把所有的点设置成小的
                for (int i = 0; i < listDot.size(); i++) {
                    listDot.get(i).setImageResource(R.mipmap.dot_1);
                    listDot.get(i).setEnabled(true);
                }
                listDot.get(position).setImageResource(R.mipmap.dot);
                listDot.get(position).setEnabled(false);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    class HeadView {
        private View headViews;

        public HeadView() {
            initView();
            initDatas();
        }

        private void initDatas() {
            /**
             * head ViewPager
             */
            headViewPagerAdapter = new HomeHeadViewPagerAdapter(list);
            vpHomeHeadImg.setAdapter(headViewPagerAdapter);
            /**
             * 分类的GridView
             */
            for (int i = 0; i < Variable.CATEGORY_NAME.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("img", Variable.CATEGORY_RES[i]);
                map.put("name", Variable.CATEGORY_NAME[i]);
                simpleAdapterlist.add(map);
            }
            simpleAdapter = new SimpleAdapter(getActivity(), simpleAdapterlist, R.layout.item_home_category_gridview, new String[]{"name", "img"}, new int[]{R.id.tv_item_home_category, R.id.iv_item_home_category});
            gvHomeHeadCategory.setAdapter(simpleAdapter);
            //添加点击事件
            gvHomeHeadCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 1){
                        //点击了 抢鲜
                        Intent intent = new Intent(getActivity(),QiangxianActivity.class);
                        startActivity(intent);
                    }
                }
            });
        }

        private void initView() {
            headViews = getActivity().getLayoutInflater().inflate(R.layout.home_head_layout, null);
            vpHomeHeadImg = (ViewPager) headViews.findViewById(R.id.vp_home_head_img);
            gvHomeHeadCategory = (GridView) headViews.findViewById(R.id.gv_home_head_category);
            llHomeHead = (LinearLayout) headViews.findViewById(R.id.ll_home_head);
            llHomeHorizontalProductBanner = (LinearLayout) headViews.findViewById(R.id.ll_home_horizontal_product_banner);
            myGridView = (AsymmetricGridView) headViews.findViewById(R.id.gv_home_mix_product_banner);
            llDot = (LinearLayout) headViews.findViewById(R.id.ll_bottom);
        }

        public View getHeadViews(){
            return headViews;
        }
    }

}
